import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:fsharing/core/viewmodels/app_model.dart';
import 'package:fsharing/core/viewmodels/pages/mine/login_model.dart';
import 'package:fsharing/core/viewmodels/pages/mine/store_logo_query_model.dart';
import 'package:fsharing/core/viewmodels/view_model.dart';
import 'package:fsharing/ui/widgets/background_container.dart';
import 'package:oktoast/oktoast.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  TextEditingController _usernameController;
  TextEditingController _passwordController;

  @override
  void initState() {
    super.initState();
    _usernameController = TextEditingController();
    _passwordController = TextEditingController();

    _getUsername().then((value) {
      _usernameController.text = value ?? '';
    });
  }

  @override
  void dispose() {
    _usernameController.dispose();
    _passwordController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(
          create: (context) => StoreLogoQueryModel(Provider.of(context, listen: false)),
        ),
        ChangeNotifierProvider(
          create: (context) => LoginModel(Provider.of(context, listen: false)),
        )
      ],
      child: BackgroundContainer(
        name: 'assets/images/all_background_oauth.png',
        child: Scaffold(
          body: SingleChildScrollView(
            padding: EdgeInsets.symmetric(horizontal: 15),
            child: Column(
              children: <Widget>[
                Container(
                  margin: EdgeInsets.only(top: 100),
                  child: Consumer<StoreLogoQueryModel>(
                    builder: (context, model, child) {
                      switch (model.viewState) {
                        case ViewState.success:
                          return CachedNetworkImage(
                            imageUrl: model.data,
                            width: 110,
                            height: 55,
                            fit: BoxFit.contain,
                          );
                        default:
                          return SizedBox(
                            width: 110,
                            height: 55,
                          );
                      }
                    },
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(top: 16),
                  child: Text(
                    '帮你开启财富自由之路',
                    style: TextStyle(color: Colors.grey, fontSize: 18),
                  ),
                ),
                Text(
                  'Help you open the way to wealth freedom',
                  style: TextStyle(color: Colors.grey, fontSize: 12),
                ),
                _WrapContainer(
                  margin: EdgeInsets.only(top: 55),
                  child: TextFormField(
                    controller: _usernameController,
                    decoration: InputDecoration(
                      hintText: '账户',
                    ),
                    textAlign: TextAlign.center,
                  ),
                ),
                _WrapContainer(
                  margin: EdgeInsets.only(top: 15),
                  child: TextFormField(
                    controller: _passwordController,
                    decoration: InputDecoration(
                      hintText: '密码',
                    ),
                    textAlign: TextAlign.center,
                    obscureText: true,
                  ),
                ),
                SizedBox(height: 8),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    FlatButton(
                      onPressed: () {
                        Navigator.of(context).pushNamed('/register');
                      },
                      child: Text(
                        '快速注册>',
                        style: TextStyle(color: Colors.grey, fontSize: 16),
                      ),
                    ),
                    FlatButton(
                      onPressed: () {
                        Navigator.of(context).pushNamed('/forget');
                      },
                      child: Text(
                        '忘记密码>',
                        style: TextStyle(color: Colors.grey, fontSize: 16),
                      ),
                    ),
                  ],
                ),
                Container(
                  margin: EdgeInsets.only(top: 16),
                  width: 256,
                  height: 65,
                  child: Consumer<LoginModel>(
                    builder: (context, model, child) {
                      switch (model.viewState) {
                        case ViewState.busy:
                          return RaisedButton(
                            onPressed: null,
                            child: CircularProgressIndicator(),
                          );
                        default:
                          return RaisedButton(
                            onPressed: () => _login(context, model),
                            child: Text(
                              '登录',
                              style: TextStyle(fontSize: 18),
                            ),
                          );
                      }
                    },
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Future<String> _getUsername() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    return sharedPreferences.getString('username');
  }

  Future<bool> _setUsername(String username) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    return await sharedPreferences.setString('username', username);
  }

  void _login(BuildContext context, LoginModel model) async {
    var username = _usernameController.text;
    var password = _passwordController.text;
    // 保存账号
    await _setUsername(username);
    // 登录
    LoginModel loginModel = Provider.of(context, listen: false);
    ViewState viewState = await loginModel.oauthToken(username, password);
    switch (viewState) {
      case ViewState.error:
        showToast(model.errorMessage);
        break;
      default:
        // 重置当前店铺
        AppStoreModel appStoreModel = Provider.of(context, listen: false);
        appStoreModel.currentStoreId = null;
        // 标记登录成功
        AppLoginModel appLoginModel = Provider.of(context, listen: false);
        appLoginModel.isLogin = true;
        // 返回
        Navigator.of(context).pop(true);
        break;
    }
  }
}

class _WrapContainer extends StatelessWidget {
  final EdgeInsetsGeometry margin;
  final Widget child;

  _WrapContainer({
    Key key,
    this.margin,
    this.child,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.center,
      padding: EdgeInsets.symmetric(horizontal: 16),
      color: Colors.white10,
      height: 50,
      margin: margin,
      child: child,
    );
  }
}
